package iut2.sponsor.server;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Servlet implementation class for Servlet: UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 8305367618713715640L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		FileItem uploadItem = getFileItem(request);
		if (uploadItem == null) {
			response.getWriter().write("NO-SCRIPT-DATA");
			return;
		}
		int i = 0;
		String fileName = new String();
		do 
		{
			i++;
			fileName  = "Logos/logo" + i + ".jpg";
		} while ((new File(fileName)).exists());
		try {
			File saveTo = new File(fileName);
			uploadItem.write(saveTo);
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write("NO-SCRIPT-DATA");
			return;
		}
		response.getWriter().write(fileName);
	}

	@SuppressWarnings("unchecked")
	private FileItem getFileItem(HttpServletRequest request) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
					return item;
				}
			}
		} catch (FileUploadException e) {
			return null;
		}
		return null;
	}

	public void generateThumbnail(String inputFileStr,
			String outputFileStr, int maxDim) throws Exception {

		int[] dimensions = new int[2];

		// Get the image from a file.
		File outputFile = new File(outputFileStr);
		Image inImage = new ImageIcon(inputFileStr).getImage();

		// Determine the scale.
		double scale = (double) maxDim / (double) inImage.getHeight(null);
		if (inImage.getWidth(null) > inImage.getHeight(null)) {
			scale = (double) maxDim / (double) inImage.getWidth(null);
		}
		scale = Math.min(scale, 1.0d);
		// Determine size of new image.
		// One of them
		// should equal maxDim.
		int scaledW = (int) (scale * inImage.getWidth(null));
		int scaledH = (int) (scale * inImage.getHeight(null));
		dimensions[0] = scaledW;
		dimensions[1] = scaledH;

		// Create an image buffer in
		// which to paint on.
		BufferedImage outImage = new BufferedImage(scaledW, scaledH,
				BufferedImage.TYPE_INT_RGB);

		// Set the scale.
		AffineTransform tx = new AffineTransform();

		// If the image is smaller than
		// the desired image size,
		// don't bother scaling.
		if (scale < 1.0d) {
			tx.scale(scale, scale);
		}

		// Paint image.
		Graphics2D g2d = outImage.createGraphics();
		g2d.drawImage(inImage, tx, null);
		g2d.dispose();

		// JPEG-encode the image
		// and write to file.
		
		OutputStream os = new FileOutputStream(outputFile);

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		encoder.encode(outImage);
		os.close();
		inImage.flush();
		outImage.flush();
	}
}